#include <iostream>
#include "RingQueue.hpp"
#include "Task.hpp"
#include <unistd.h>
struct ThreadData
{
    RingQueue<Task> *rq;
    std::string pathname;
};
void *Cosumer(void *args)
{
    // std::cout << "enter cosumer" << std::endl;
    ThreadData *td = static_cast<ThreadData *>(args);
    RingQueue<Task> *rq = td->rq;
    std::string name = td->pathname;
    // std::cout << "will enter while(cosumer)" << std::endl;

    while (true)
    {
        Task t;
        rq->Pop(&t);
        t();
        std::cout << "Consumer get task, task is : " << t.GetTask() << " who: " << name << " result: " << t.GetResult() << std::endl;
        sleep(1);
    }
    return nullptr;
}

void *Productor(void *args)
{
    // std::cout << "enter productor" << std::endl;
    ThreadData *td = static_cast<ThreadData *>(args);
    RingQueue<Task> *rq = td->rq;
    std::string name = td->pathname;
    int len = opers.size();
    // std::cout << "will enter while(productor)" << std::endl;

    while (true)
    {
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 10;
        char op = opers[rand() % len];
        Task t(data1, data2, op);
        // std::cout << "Task create done" << std::endl;

        rq->Push(t);

        std::cout << "Productor task done, task is : " << t.GetTask() << " who: " << name << std::endl;
        sleep(1);
    }
    return nullptr;
}
int main()
{
    srand(time(nullptr));
    RingQueue<Task> *rq = new RingQueue<Task>(50);
    pthread_t c[5], p[3];
    for (int i = 0; i < 5; i++)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->pathname = "Conssumer" + std::to_string(i);
        pthread_create(c + i, nullptr, Cosumer, td);
    }
    // std::cout << "Conssumer thread done?" << std::endl;
    for (int i = 0; i < 3; i++)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->pathname = "Productor" + std::to_string(i);
        pthread_create(p + i, nullptr, Productor, td);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_join(c[i], nullptr);
    }
    for (int i = 0; i < 3; i++)
    {
        pthread_join(p[i], nullptr);
    }
    delete rq;
    return 0;
}